
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
        @selection-change="selectionChange"
      >
        <template
          slot="cleanTime"
          slot-scope="scope"
        >
          {{scope.row.beginTime}} ~ {{scope.row.endTime}}
        </template>
        <template slot="menuRight">
          <el-button
            type="primary"
            size="small"
            @click="dialogVisibleMonth = true"
          >生成月度报表</el-button>
          <el-button
            v-if="permissionList.autoClean"
            type="primary"
            size="small"
            @click="dialogVisible = true"
          >系统自动清分</el-button>
          <!-- <el-button
            v-if="permissionList.reClean"
            type="primary"
            size="small"
            :loading="loading"
            @click="handleReClean"
	        hidden="hidden"
          >重新清分</el-button> -->
          <el-button
            v-if="permissionList.genReport"
            type="primary"
            size="small"
            @click="handeGenReportVisible = true"
          >生成应收应付差异统计表</el-button>
        </template>>
      </avue-crud>
    </basic-container>
    <el-dialog
      title="生成月度报表"
      width="500px"
      :visible.sync="dialogVisibleMonth"
    >
      <avue-form
        ref="form"
        v-model="autoClearMonth"
        :option="optionMonth"
        @submit="submitMonth"
      >
      </avue-form>
    </el-dialog>
    <el-dialog
      title="系统自动清分"
      width="500px"
      :visible.sync="dialogVisible"
    >
      <avue-form
        ref="form"
        v-model="autoCleanForm"
        :option="option"
        @submit="submit"
      >
      </avue-form>
    </el-dialog>
    <el-dialog
      title="生成应收应付差异统计表"
      width="500px"
      :visible.sync="handeGenReportVisible"
    >
      <avue-form
        ref="form"
        v-model="genForm"
        :option="genOption"
        @submit="genSubmit"
      >
      </avue-form>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, autoClean, reClean,isReClean, genReport,autoClearMonth } from '@/api/rca/swckcleardetail'
import { tableOptions } from '@/const/crud/rca/swckcleardetail'
import { mapGetters } from 'vuex'
import { dateFormat } from '@/util/date';

export default {
  name: 'swckcleardetail',
  data () {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,

      extraParam: {
        detailType: "normal",
      },
      selection: [],
      dialogVisible: false,
      dialogVisibleMonth: false,
      handeGenReportVisible: false,
      autoCleanForm: {},
      autoClearMonth: {},
      genForm: {},
      loading: false
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList () {
      return {
        genReport: this.vaildData(this.permissions.sw_ck_clear_detail_genReport, false),
        autoClean: this.vaildData(this.permissions.sw_ck_clear_detail_autoClean, false),
        reClean: this.vaildData(this.permissions.sw_ck_clear_detail_reClean, false)
      };
    },
    tableOption () {
      return tableOptions[this.extraParam.detailType]
    },
    optionMonth () {
      return {
        submitText: '确认',
        column: [{
          label: "报表生成时间",
          prop: "startDate",
          type: "month",
          span: 24,
          valueFormat: 'yyyy-MM',
          labelWidth: 120,
          placeholder: "请选择生成时间",
          rules: [{
            required: true,
            message: "请选择生成时间",
            trigger: "change"
          }],
        }]
      }
    },
    option () {
      return {
        submitText: '确认',
        column: [{
          label: "清分开始时间",
          prop: "startDate",
          type: "date",
          span: 24,
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          labelWidth: 120,
          placeholder: "请选择清分开始时间",
          rules: [{
            required: true,
            message: "请选择清分开始时间",
            trigger: "change"
          }],
          pickerOptions: {
            disabledDate: (time) => {
              return time.getTime() > Date.now() || (this.autoCleanForm.startDate && time.getTime() > new Date(this.autoCleanForm.startDate).getTime());
            },
          }
        }, {
          label: "清分结束时间",
          prop: "endDate",
          type: "date",
          span: 24,
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          labelWidth: 120,
          placeholder: "请选择清分结束时间",
          rules: [{
            required: true,
            message: "请选择清分结束时间",
            trigger: "change"
          }],
          pickerOptions: {
            disabledDate: (time) => {
              let now = new Date(this.autoCleanForm.startDate);
              now.setDate((now.getDate() - 1));
              return time.getTime() > Date.now() || (this.autoCleanForm.startDate && time.getTime() < now.getTime());
            },
          }
        }]
      }
    },
    genOption () {
      return {
        submitText: '确认',
        column: [{
          label: "开始时间",
          prop: "startDate",
          type: "date",
          span: 24,
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          labelWidth: 120,
          placeholder: "请选择开始时间",
          rules: [{
            required: true,
            message: "请选择开始时间",
            trigger: "change"
          }],
          pickerOptions: {
            disabledDate: (time) => {
              return time.getTime() > Date.now() || (this.genForm.startDate && time.getTime() > new Date(this.genForm.startDate).getTime());
            },
          }
        }, {
          label: "结束时间",
          prop: "endDate",
          type: "date",
          span: 24,
          format: 'yyyy-MM-dd',
          valueFormat: 'yyyy-MM-dd',
          labelWidth: 120,
          placeholder: "请选择结束时间",
          rules: [{
            required: true,
            message: "请选择结束时间",
            trigger: "change"
          }],
          pickerOptions: {
            disabledDate: (time) => {
              let now = new Date(this.genForm.startDate);
              now.setDate((now.getDate() - 1));
              return time.getTime() > Date.now() || (this.genForm.startDate && time.getTime() < now.getTime());
            },
          }
        }]
      }
    }
  },
  watch: {
    detailType: function () {
      this.$refs.crud.searchReset();
      this.page.currentPage = 1;
      this.getList(this.page);
    },
  },
  methods: {
    //生成月度报表
    async submitMonth (params, done) {
      await autoClearMonth(params)
        .then(data => {
          this.$message.success('操作成功');
          done()
          this.dialogVisibleMonth = false
        }).catch(error=> {
          if(error.message.indexOf('timeout')!=-1){
            this.$message.warning('生成生成月度报表需要一定时间，请稍后查看!')
            done()
            this.dialogVisibleMonth = false
          }else{
            this.$message.error('操作失败!')
            done()
            this.dialogVisibleMonth = false
          }
        });
    },
    async submit (params, done) {

      //点击正常清分数据，调用后台验证是否存在，如果存在进行提示，如果不存在，则不提示，直接进行清分
      await isReClean(params)
          .then(async (res) => {
            let data = res.data.data;
            if(data.length>0){
              this.$confirm("是否确认重新清分?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }).then(async () => {
                  await autoClean(params)        
                    .then(data => {
                      this.$message.success('操作成功');
                      done()
                      this.dialogVisible = false
                      this.refreshChange()
                    }).catch(error=> {
                      if(error.message.indexOf('timeout')!=-1){
                        this.$message.warning('系统自动清分需要一定时间，请稍后查看!')
                        done()
                        this.dialogVisible = false
                        this.refreshChange()
                      }else{
                        done()
                      }
                    });
                }).catch(action => {
                    if (action === 'cancel'){
                        done()
                        this.dialogVisible = false
                    }
                });
            }else{
              await autoClean(params)        
                    .then(data => {
                      this.$message.success('操作成功');
                      done()
                      this.dialogVisible = false
                      this.refreshChange()
                    }).catch(error=> {
                      if(error.message.indexOf('timeout')!=-1){
                        this.$message.warning('系统自动清分需要一定时间，请稍后查看!')
                        done()
                        this.dialogVisible = false
                        this.refreshChange()
                      }else{
                        done()
                      }
                    });
            }
          }).catch(error=> {

          });



    },
    async genSubmit (params, done) {
      // await genReport(params);
      // this.$message.success('操作成功');
      // done()
      await genReport(params)
        .then(data => {
          this.$message.success('操作成功');
          done()
          this.handeGenReportVisible = false
        }).catch(error=> {
          if(error.message.indexOf('timeout')!=-1){
            this.$message.warning('生成财务报表需要一定时间，请稍后查看!')
            done()
            this.handeGenReportVisible = false
          }else{
            this.$message.error('操作失败!')
            done()
            this.handeGenReportVisible = false
          }
        });
    },
    selectionChange (list) {
      this.selection = list.map(l => l.id);
    },
    handleReClean () {
      if (this.selection.length === 0) {
        this.$message.error('请选择要重新清分的记录');
        return;
      }
      this.$confirm("确认要重新清分?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.tableLoading =true;
        this.loading =true;
        // reClean({
        //   ids: this.selection,
        // });
        // this.$message.success('操作成功，后台正在进行清分，请稍等');
        // this.getList(this.page);
        reClean({
          ids: this.selection,
        }).then(data => {
          this.$message.success('操作成功');
          this.tableLoading =false;
          this.loading =false;
          this.getList(this.page);
        }).catch(error=> {
          if(error.message.indexOf('timeout')!=-1){
            this.$message.warning('操作成功，后台正在进行清分，请稍等');
            this.tableLoading =false;
            this.loading =false;
            this.getList(this.page);
          }else{
            this.$message.error('操作失败!')
            this.tableLoading =false;
            this.loading =false;
            this.getList(this.page);
          }
        })
      });
    },
    async getList (page, params) {
      this.tableLoading = true
      const [startDate, endDate] = this.searchForm.cleanTime || [];
      try {
        const response = await fetchList(Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm,
          { startDate, endDate }
        ))

        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      } catch (e) {
        this.tableLoading = false
      }
    },
    async searchChange (form, done) {
      this.searchForm = { ...form };
      try {
        await this.getList(this.page, form);
      } finally {
        done();
      }
    },
    refreshChange () {
      this.getList(this.page)
    },
    searchReset () {
      this.page.currentPage = 1
      this.getList(this.page);
    },
  }
}
</script>
